//
//  KSPickerPhotoViewController.swift
//  Supermarket
//
//  Created by Black_Crystal on 2017/9/19.
//  Copyright © 2017年 kushao. All rights reserved.
//

import UIKit
import Photos

protocol PickerPhotoDelegate: NSObjectProtocol {
    func pickerPhoto(asset: [PHAsset])
    func pickerTempPhoto(asset: [PHAsset])
}

class KSPickerPhotoViewController: KSBaseViewController,CompleteDelegate,UINavigationControllerDelegate {
    
    let toolViewHeight: CGFloat = 50
    
    var collectionView: UICollectionView!
    
    var completeView: KSPickerPhotoBottomView!
    
    //取得的资源结果，用了存放的PHAsset
    var assetsFetchResults:PHFetchResult<PHAsset>?
    var selectPhotoResults: [PHAsset] = []
    var tempSelect: [PHAsset] = []
    var cameraChooseNumber: Int = Int.max
    //带缓存的图片管理对象
    var imageManager:PHCachingImageManager!
    
    //缩略图大小
    var assetGridThumbnailSize:CGSize!
    
    //每次最多可选择的照片数量
    var maxSelected:Int = Int.max
    
    weak var delegate: PickerPhotoDelegate?
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.isHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let backBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 9, height: 16))
        backBtn.setBackgroundImage(UIImage.init(named: "Common_Back"), for: .normal)
        backBtn.addTarget(self, action: #selector(popViewControllerEvent), for: .touchDown)
        let item = UIBarButtonItem.init(customView: backBtn)
        self.navigationItem.leftBarButtonItem = item
        
        let rightBtn = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 50, height: 64))
        rightBtn.setTitle("取消", for: .normal)
        rightBtn.setTitleColor(UIColor.blue, for: .normal)
        rightBtn.addTarget(self, action: #selector(cancel), for: .touchDown)
        let rightBarItem = UIBarButtonItem.init(customView: rightBtn)
        self.navigationItem.rightBarButtonItem = rightBarItem
        
        let layout = UICollectionViewFlowLayout()
        self.collectionView = UICollectionView.init(frame: CGRect.init(x: 0, y: 0, width: KSConstants.kScreenWidth, height: KSConstants.kScreenHeight - toolViewHeight), collectionViewLayout: layout)
        self.collectionView.contentInset = UIEdgeInsetsMake(10, 10, 10, 10)
        self.collectionView.delegate = self
        self.collectionView.dataSource = self
        
        self.collectionView.register(KSPickerPhotoCollectionViewCell.self, forCellWithReuseIdentifier: "KSPickerPhotoCollectionViewCell")
        self.collectionView.backgroundColor = UIColor.white
        self.view.addSubview(collectionView)
        
        assetGridThumbnailSize = CGSize.init(width: KSConstants.kScreenWidth/4, height: KSConstants.kScreenWidth/4)
        self.collectionView.reloadData()
        
        self.imageManager = PHCachingImageManager()
        self.resetCacheedAssets()
        
        self.collectionView.allowsMultipleSelection = true
        
        self.completeView = KSPickerPhotoBottomView.init(frame: CGRect.init(x: 0, y: KSConstants.kScreenHeight - toolViewHeight, width: KSConstants.kScreenWidth, height: toolViewHeight))
        completeView.delegaet = self
        if tempSelect.count > 0 {
            completeView.numLabel.text = "\(tempSelect.count)"
            completeView.playAnimate()
        }
        self.view.addSubview(completeView)
        
        
    }
    
    @objc func popViewControllerEvent() {
        self.delegate?.pickerTempPhoto(asset: tempSelect)
        self.navigationController?.popViewController(animated: true)
    }
    
    func completeCallBack() {
        var assets:[PHAsset] = []
        if let indexPaths = self.collectionView.indexPathsForSelectedItems{
            for indexPath in indexPaths{
                assets.append(assetsFetchResults![indexPath.row] )
            }
        }
        self.navigationController?.dismiss(animated: true, completion: {
            self.selectPhotoResults = self.tempSelect
            self.delegate?.pickerPhoto(asset: self.selectPhotoResults)
        })
    }
    
    @objc func cancel() {
        //退出当前视图控制器
        self.navigationController?.dismiss(animated: true, completion: nil)
    }
    
    // 重置缓存
    func resetCacheedAssets() {
        self.imageManager.stopCachingImagesForAllAssets()
    }
    
    //获取已选择个数
    func selectedCount() -> Int {
        return self.collectionView.indexPathsForSelectedItems?.count ?? 0
    }
    
    //完成按钮点击
    func finishSelect(){
        //取出已选择的图片资源
        var assets:[PHAsset] = []
        if let indexPaths = self.collectionView.indexPathsForSelectedItems{
            for indexPath in indexPaths{
                assets.append(assetsFetchResults![indexPath.row] )
            }
        }
        //调用回调函数
        self.navigationController?.dismiss(animated: true, completion: {
            self.delegate?.pickerPhoto(asset: self.selectPhotoResults)
        })
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
}

extension KSPickerPhotoViewController: UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: (KSConstants.kScreenWidth - 50)/4, height: (KSConstants.kScreenWidth - 50)/4)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.assetsFetchResults?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "KSPickerPhotoCollectionViewCell", for: indexPath) as! KSPickerPhotoCollectionViewCell
        let asset = self.assetsFetchResults![indexPath.row]
        print(indexPath.row)
        if self.tempSelect.contains(asset) {
            cell.setSelectImage(iselected: true)
        } else {
            cell.setSelectImage(iselected: false)
        }
        
        self.imageManager.requestImage(for: asset, targetSize: assetGridThumbnailSize, contentMode: .aspectFit, options: nil) { (image, nfo) in
            cell.imageView.image = image
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let asset = self.assetsFetchResults![indexPath.row]
        
        //如果选择的个数大于最大选择数
            if tempSelect.contains(asset) {
                for i in 0...tempSelect.count - 1 {
                    let tempAsset = tempSelect[i]
                    if tempAsset == asset {
                        tempSelect.remove(at: i)
                        if tempSelect.count > 0 {
                            completeView.numLabel.text = "\(tempSelect.count)"
                            completeView.playAnimate()
                        } else {
                            completeView.isHidden = true
                        }
                        let indexPathArray: [IndexPath] = [indexPath]
                        self.collectionView.reloadItems(at: indexPathArray)
                        return
                    }
                }
            } else if (tempSelect.count + self.cameraChooseNumber) == self.maxSelected {
                //设置为不选中状态
                collectionView.deselectItem(at: indexPath, animated: false)
                //弹出提示
                let title = "你最多只能选择\(self.maxSelected - self.cameraChooseNumber)张照片"
                let alertController = UIAlertController(title: title, message: nil,
                                                        preferredStyle: .alert)
                
                let cancelAction = UIAlertAction(title:"我知道了", style: .cancel,
                                                 handler:nil)
                alertController.addAction(cancelAction)
                self.present(alertController, animated: true, completion: nil)
                
            } else {
                tempSelect.append(asset)
                let indexPathArray: [IndexPath] = [indexPath]
                self.collectionView.reloadItems(at: indexPathArray)
                completeView.numLabel.text = "\(tempSelect.count)"
                completeView.playAnimate()
        }
    }
}

